<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="12" :sm="24">
            <a-input-search style="max-width:500px" placeholder="多个敏感词用英文逗号隔开" @search="AddClick" >
              <a-button type="primary" slot="enterButton">批量添加</a-button>
            </a-input-search>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-input-search style="max-width:500px" placeholder="请输入敏感词关键字" @search="onSearch" >
              <a-button type="primary" slot="enterButton" icon="search">搜索</a-button>
            </a-input-search>
          </a-col>
        </a-row>
      </a-form>
      <div style="padding: 20px 0">
        <div style="float:left;margin-right:30px">
          <upload-model @modelTxt="modelTxt">
            <span>批量导入</span>
          </upload-model>
        </div>
        <div style="float:left;">
          <a-button type="primary" :loading="confirmLoading" @click="modelOutClick"> <a-icon type="upload" /> 导出模板</a-button>
        </div>
        <p class="clear"></p>
      </div>
    </div>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :pagination="pagination"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="text" slot-scope="text">
        <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
      </span>
      <span slot="createTime" slot-scope="text">
        <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a-popconfirm
            title="删除不可恢复，确定删除？"
            @confirm="handleSub(record)"
            @cancel="cancel"
            okText="确定"
            cancelText="取消">
            <a href="#">删除</a>
          </a-popconfirm>
        </template>
      </span>
    </s-table>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import UploadModel from '@/viewsVue/commit/UploadModel'
import { sensitiveList } from '@/api/data'
import utils from '@/utils/common'
import { mapActions } from 'vuex'
import moment from 'moment'
var timeStamp = Number(new Date())

export default {
  name: 'ReviewList',
  components: {
    STable,
    Ellipsis,
    UploadModel
  },
  data () {
    return {
      confirmLoading: false,
      // 查询参数
      dataSource: [],
      queryParam: {},
      keyword: '',
      pagination: {
        current: 1,
        pageSize: 20
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '关键词',
          dataIndex: 'text',
          scopedSlots: { customRender: 'text' }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: pagination => {
        return sensitiveList(Object.assign(pagination, this.queryParam)).then(res => {
          if (res.data.list && res.data.list.length !== 0) {
            this.dataSource = res.data.list
          }
          return res.data
        })
      }
    }
  },
  created () {
    this.queryParam = {
      token: utils.AuthToken(timeStamp, this.$store.getters.userKey),
      timestamp: timeStamp,
      adminId: this.$store.getters.adminId,
      keyword: this.keyword
    }
  },
  methods: {
    ...mapActions(['SensitiveDelete', 'SensitiveAdd']),
    moment,
    modelTxt () { // 模板导入成功
      this.$refs.table.refresh()
    },
    AddClick (val) { // 添加敏感词
      if (val) {
        this.SensitiveAdd({ words: JSON.stringify(val.split(',')) })
          .then((res) => this.ApiSuccess(res, 'add'))
          .catch(err => this.requestFailed(err))
      } else {
        this.$message.warning('请输入敏感词')
      }
    },
    onSearch (val) { // 搜索
      this.queryParam.keyword = val
      this.$refs.table.refresh()
    },
    modelOutClick () { // 批量导出模板
      this.confirmLoading = true
      if (this.dataSource.length === 0) {
        this.$notification['warning']({
          message: '失败',
          description: '无敏感词列表，无法导出',
          duration: 4
        })
      } else {
        var data = []
        for (var i in this.dataSource) {
          data.push(this.dataSource[i].text + '\r\n')
        }
        var tempString = data.join('')
        utils.exportRaw('敏感词.txt', tempString)
      }
      setTimeout(() => {
        this.confirmLoading = false
      }, 2000)
    },
    cancel () {},
    handleSub (record) { // 删除敏感词
      this.SensitiveDelete({ id: record.id })
        .then((res) => this.ApiSuccess(res))
        .catch(err => this.requestFailed(err))
    },
    ApiSuccess (res, val) {
      if (res.status === 200 || res.status === '200') {
        var desc = '删除成功'
        if (val) {
          desc = '添加成功'
        }
        this.$notification['success']({
          message: '成功',
          description: desc,
          duration: 4
        })
        this.$refs.table.refresh()
      } else {
        this.requestFailed(res)
      }
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>
